<template>
  <view class="chart-section">
    <!-- 时间选择器 -->
    <TimeSelector
      :periods="timePeriods"
      :active-index="activePeriod"
      @change="switchPeriod"
    />

    <!-- 数据图表 -->
    <view class="chart-container">
      <view :id="chartId" :style="{ width: '100%', height: chartHeight }">
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from "vue";
import TimeSelector from "./TimeSelector.vue";
import * as echarts from "echarts/dist/echarts.esm.js";
import {
  commonApi,
  wztcApi,
  xfzdApi,
  rymjApi,
  nljsApi,
  gkhzApi,
} from "@/api/index.js";
// Props 定义（保留必要的配置项，移除数据相关的 props）
const props = defineProps({
  type: {
    type: String,
    default: "",
  },
  // 图表 ID
  chartId: {
    type: String,
    default: "main",
  },
  // 图表高度
  chartHeight: {
    type: String,
    default: "400rpx",
  },
});

// Emits 定义
const emit = defineEmits(["period-change"]);

// 组件内部响应式数据
// 时间周期
const timePeriods = ref(["今天", "近七天"]);
// 当前激活的周期索引
const activePeriod = ref(0);
// 图表数据映射（根据不同时间周期对应不同数据）
const chartDataMap = ref({
  0: {
    // 今天
    xAxis: ["00:00", "04:00", "08:00", "12:00", "16:00", "20:00"],
    series: [120, 150, 80, 210, 130, 180],
  },
  1: {
    // 近七天
    xAxis: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"],
    series: [320, 350, 280, 410, 330, 380, 420],
  },
});
const types = {
  //占道经营
  street_occupation: "占道经营",
  //消防占道
  fire_road_block: "消防占道",
  //违章停车
  illegal_parking: "违章停车",
  //人员密集
  crowd_density: "人员密集",
  //内涝积水专题
  waterlogging: "内涝积水专题",
  //高空火灾
  high_altitude_fire: "高空火灾",
  //垃圾暴露
  garbage_exposure: "垃圾暴露",
  //垃圾桶满溢
  bin_overflow: "垃圾桶满溢",
  //流浪乞讨
  homeless: "流浪乞讨",
  //出店经营
  storefront_business: "出店经营",
};
// ECharts 实例
let chartInstance = null;

// 更新图表配置
const updateChart = (xList, data) => {
  if (!chartInstance) return;

  const option = {
    backgroundColor: "transparent",
    grid: {
      left: "10%",
      right: "10%",
      bottom: "15%",
      top: "15%",
    },
    xAxis: {
      type: "category",
      data: xList,
      axisTick: { show: false },
      axisLine: {
        lineStyle: { color: "#E5E5E5" },
      },
      axisLabel: {
        color: "#999",
        fontSize: 10,
      },
    },
    yAxis: {
      type: "value",
      position: "left",
      axisLine: { show: false },
      axisTick: { show: false },
      axisLabel: {
        color: "#999",
        fontSize: 10,
      },
      splitLine: {
        lineStyle: { color: "#F0F0F0" },
      },
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
    },
    series: [
      {
        name: types[props.type],
        type: "line",
        yAxisIndex: 0,
        data: data,
        lineStyle: {
          color: "#50C8FF",
          width: 2,
        },
        itemStyle: {
          color: "#50C8FF",
        },
        symbol: "circle",
        symbolSize: 6,
      },
    ],
  };
  chartInstance.setOption(option);
};
const updateChart2 = (xList, data) => {
  let series = [];
  data.forEach((item) => {
    const colors = ["#50C8FF", "#FF9800", "#FF5722", "#9C27B0", "#3F51B5"];
    series.push({
      name: item.name,
      type: "line",
      yAxisIndex: 0,
      data: item.data,
      lineStyle: {
        color: colors[series.length],
        width: 2,
      },
      itemStyle: {
        color: colors[series.length],
      },
      symbol: "circle",
      symbolSize: 6,
    });
  });

  const option = {
    backgroundColor: "transparent",
    grid: {
      left: "10%",
      right: "10%",
      bottom: "15%",
      top: "15%",
    },
    xAxis: {
      type: "category",
      data: xList,
      axisTick: { show: false },
      axisLine: {
        lineStyle: { color: "#E5E5E5" },
      },
      axisLabel: {
        color: "#999",
        fontSize: 10,
      },
    },
    legend: {
      data: series.map((item) => item.name),
      textStyle: {
        color: "#999",
        fontSize: 10,
      },
    },
    yAxis: {
      type: "value",
      position: "left",
      axisLine: { show: false },
      axisTick: { show: false },
      axisLabel: {
        color: "#999",
        fontSize: 10,
      },
      splitLine: {
        lineStyle: { color: "#F0F0F0" },
        show: false,
      },
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
    },
    series,
  };
  chartInstance.setOption(option);
};
// 切换时间周期
const switchPeriod = (index) => {
  activePeriod.value = index;
  if (index === 0) {
    getWarningDayData();
  } else {
    getWarningDay7Data();
  }
};

// 初始化图表
const initChart = () => {
  nextTick(() => {
    const chartDom = document.getElementById(props.chartId);
    if (chartDom) {
      chartInstance = echarts.init(chartDom);
      getWarningDayData();
    }
  });
};
//获取人员密集预警分析
const getrymjData = async (isWeek) => {
  let res = {};
  if (isWeek) {
    res = await rymjApi.getWarningDay7();
  } else {
    res = await rymjApi.getWarningDay();
  }
  if (res.data) {
    const data = res.data;
    let xList = data.map((item) => item["时间"]);
    let series = [
      {
        name: "实际人流",
        data: data.map((item) => item["实际人流"]),
      },
      {
        name: "预测人流",
        data: data.map((item) => item["预测人流"]),
      },
      {
        name: "安全容量",
        data: data.map((item) => item.rl),
      },
    ];
    updateChart2(xList, series);
  }
};

//获取预警通知分析今日数据
const getWarningDayData = async () => {
  if (props.type === "crowd_density") {
    getrymjData();
    return;
  }
  let res = {};
  if (props.type === "fire_road_block") {
    //-消防占道
    res = await xfzdApi.getWarningDay();
  } else if (props.type === "illegal_parking") {
    //-违章停车
    res = await wztcApi.getWarningDay();
  } else if (props.type === "waterlogging") {
    //-内涝积水
    res = await nljsApi.getWarningDay();
  } else if (props.type === "high_altitude_fire") {
    //-高空火灾
    res = await gkhzApi.getWarningDay();
  } else {
    res = await commonApi.getWarningDay();
  }
  if (res.data) {
    const data = res.data;
    let xList = [];
    let series = [];
    if (props.type == "illegal_parking") {
      //-违章停车
      xList = data.map((item) => item.sj);
    } else {
      xList = data.map((item) => item.time);
    }
    if (props.type === "storefront_business") {
      //-出店经营
      series = data.map((item) => item.cdjy);
    } else if (props.type === "garbage_exposure") {
      //-垃圾暴露
      series = data.map((item) => item.lmljjg);
    } else if (props.type === "bin_overflow") {
      //-垃圾桶满溢
      series = data.map((item) => item.ljtmy);
    } else if (props.type === "street_occupation") {
      //-占道经营
      series = data.map((item) => item.zdjy);
    } else if (props.type === "fire_road_block") {
      //-消防占道
      series = data.map((item) => item.value);
    } else if (props.type === "illegal_parking") {
      //-违章停车
      series = data.map((item) => item.alarmCount);
    } else if (props.type === "waterlogging") {
      //-内涝积水
      series = data.map((item) => item.qsjs);
    } else if (props.type === "high_altitude_fire") {
      //-高空火灾
      series = data.map((item) => item.value);
    } else if (props.type === "homeless") {
      series = data.map((item) => item.llqt);
    }
    updateChart(xList, series);
  }
};
//获取预警通知分析7日数据
const getWarningDay7Data = async () => {
  if (props.type === "crowd_density") {
    getrymjData(true);
    return;
  }
  let res = {};
  if (props.type === "fire_road_block") {
    //-消防占道
    res = await xfzdApi.getWarningDay7();
  } else if (props.type === "illegal_parking") {
    //-违章停车
    res = await wztcApi.getWarningDay7();
  } else if (props.type === "waterlogging") {
    //-内涝积水
    res = await nljsApi.getWarningDay7();
  } else if (props.type === "high_altitude_fire") {
    //-高空火灾
    res = await gkhzApi.getWarningDay7();
  } else {
    res = await commonApi.getWarningDay7();
  }
  if (res.data) {
    const data = res.data;
    let xList = [];
    let series = [];
    if (props.type == "illegal_parking") {
      //-违章停车
      xList = data.map((item) => item.sj);
    } else {
      xList = data.map((item) => item.time);
    }
    if (props.type === "storefront_business") {
      //-出店经营
      series = data.map((item) => item.cdjy);
    } else if (props.type === "garbage_exposure") {
      //-垃圾暴露
      series = data.map((item) => item.lmljjg);
    } else if (props.type === "bin_overflow") {
      //-垃圾桶满溢
      series = data.map((item) => item.ljtmy);
    } else if (props.type === "street_occupation") {
      //-占道经营
      series = data.map((item) => item.zdjy);
    } else if (props.type === "fire_road_block") {
      //-消防占道
      series = data.map((item) => item.value);
    } else if (props.type === "illegal_parking") {
      //-违章停车
      series = data.map((item) => item.alarmCount);
    } else if (props.type === "waterlogging") {
      //-内涝积水
      series = data.map((item) => item.qsjs);
    } else if (props.type === "high_altitude_fire") {
      //-高空火灾
      series = data.map((item) => item.value);
    } else if (props.type === "homeless") {
      series = data.map((item) => item.llqt);
    }
    updateChart(xList, series);
  }
};
// 组件挂载时初始化图表
onMounted(() => {
  initChart();
  if (props.type === "high_altitude_fire") {
    timePeriods.value[1] = "近15日";
  }
  // 监听窗口大小变化，调整图表大小
  window.addEventListener("resize", handleResize);
});

// 组件卸载时销毁图表实例和移除事件监听
onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }

  window.removeEventListener("resize", handleResize);
});

// 处理窗口大小变化
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize();
  }
};
</script>

<style lang="scss" scoped>
.chart-section {
  width: 100%;
}

.chart-container {
  margin: 0 30rpx;
}
</style>
